home *** CD-ROM | disk | FTP | other *** search
- Path: news.lpr.carel.fi!usenet
- From: Ari Lukumies <aril@cmt.lpr.mail.carel.fi>
- Newsgroups: comp.lang.c
- Subject: Re: Adding Arrays, anyone?
- Date: Thu, 25 Jan 1996 12:36:27 +0200
- Organization: Carelcomp Forest
- Message-ID: <31075D2B.676E@cmt.lpr.mail.carel.fi>
- References: <4e6gpm$dfb@doc.jmu.edu>
- NNTP-Posting-Host: renoir.cclahti.carel.fi
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 2.0b6a (WinNT; I)
-
- Rachel K. Warren wrote:
- >
- > Could somebody give me an example of adding two arrays together?
- > Say the first array has four mailboxes with "1" in it to, so when you
- > print it out its,"1111" and the second array has four mailboxes with the
- > number "2" in it, so that you print it out and its "2222", so I could get
- > "3333"?
- >
- > I tried something like
- >
- > for(counter =0 ; counter != '\0'; counter++)
- > printf("%c",string1[counter] + string2[counter]
- >
- > and I got a bunch of garbage on the screen.
-
- You have some bugs here. First, you're adding the ASCII codes of the two letters ('1' =
- 0x31, '2' = 0x32 -> 0x63 = 'c'). Second, your loop exit condition is wrong. If you want
- to use ASCIIZ strings, you should write (I use a temporary variable here for making
- the process more clear):
-
- int tmp;
-
- for (counter = 0; string1[counter] != '\0'; counter++) {
- tmp = (string1[counter] - '0') + (string2[counter] - '0');
- printf("%c", tmp + '0');
- }
-
- Another, and faster way, is to use pointers:
-
- char *p1 = string1;
- char *p2 = string2;
-
- while (*p1) {
- tmp = (*p1++ - '0') + (*p2++ - '0');
- printf("%c", tmp + '0');
- }
-
- However, if you'll one day have the arrays:
-
- char string1[5] = "5555";
- char string2[5] = "5555";
-
- you will have quite interesting results. So, you should switch using integer arrays:
-
- int string1[4] = { 5, 5, 5, 5 };
- int string2[4] = { 5, 5, 5, 5 };
-
- int string3[4];
-
- #define DIM(x) (sizeof(x)/sizeof(x[0]))
-
- for (counter = 0; counter < DIM(string1); counter++)
- printf("%d ", string1[counter] + string2[counter]);
-
- This, of course, works only if the arrays are of the same size. Consider the following
- code:
-
- int string1[] = { 1, 1, 1, 1 };
- int string2[] = { 2, 2, 2 };
-
- ...
-
- What do you think is the output from the for loop?
-
- Later,
- AriL
- --
- All my opinions are mine and mine alone.
-